<template>
  <div @click="indexNum = -1">
    <div class="major" style="margin-top: 10px" v-if="zyType == 1">
      <div class="major-left">专业选择</div>
      <div class="major-right">
        <el-button @click="tabXueke(2)" :class="numXueke == 2 ? 'xueke' : ''"
          >本科</el-button
        >
        <el-button @click="tabXueke(1)" :class="numXueke == 1 ? 'xueke' : ''"
          >专科</el-button
        >
      </div>
    </div>
    <div class="major" style="margin-top: 10px">
      <div class="major-left">专业选择</div>
      <div class="major-right">
        <el-popover
          v-for="(item, index) in majorList"
          :visible="indexNum == index"
          :key="index"
          placement="bottom"
          width="auto"
        >
          <template #reference>
            <div
              class="major-size alitem"
              :class="indexNum === index ? 'active' : ''"
              @click.stop="clickChange(index)"
            >
              <div>{{ item.name }}({{ item.childCount }})&nbsp;</div>
              <el-icon>
                <ArrowDown />
              </el-icon>
            </div>
          </template>
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange"
            >全部</el-checkbox
          >
          <el-checkbox-group
            v-model="tempSelMajors"
            @change="handleCheckedCitiesChange"
            style="display: flex; flex-wrap: wrap; width: 500px"
          >
            <el-checkbox
              v-for="major in item.majors"
              :key="major"
              :value="major"
              >{{ major.name }}</el-checkbox
            >
          </el-checkbox-group>
          <div class="right matop">
            <el-button @click="indexNum = -1">取消</el-button>
            <el-button type="primary" @click="onClickCheckboxConfirm"
              >确定</el-button
            >
          </div>
        </el-popover>
      </div>
    </div>

    <div class="major" style="margin-top: 10px">
      <div class="major-left">招生类型</div>
      <div class="major-right">
        <div class="df">
          <div class="select">
            <el-select
              v-model="enrollmentType"
              placeholder="请输入内容"
              size="large"
              style="width: 80px"
              @change="handleChange"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </div>
          <div class="botton" style="margin-left: 10px">
            <el-button
              @click="getStudentsTtype(item)"
              :disabled="enrollmentType == 1"
              :type="
                majorEnrollTypes.includes(item.name) ? 'primary' : 'default'
              "
              v-for="(item, index) in dataListType"
              :key="index"
              >{{ item.name }}</el-button
            >
            <span style="display: inline-block; margin: 0 10px; color: #eee"
              >|</span
            >
            <el-button :type="isShow ? 'primary' : 'default'" @click="addMojoy"
              >新增专业</el-button
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 限报要求 -->
    <div
      class="major"
      style="display: flex; align-items: center; margin-left: 8px"
    >
      <div class="major-left">
        限报要求
        <el-tooltip
          class="box-item"
          effect="dark"
          placement="bottom-start"
          style="width: 1000px; height: 500px"
        >
          <template #content>
            <img
              style="width: 1000px; height: 500px"
              src="../../../assets/images/desc.png"
              alt=""
            />
          </template>
          <img
            src="https://b.gaokaow.cc/question@2x.png"
            alt=""
            style="width: 14px; height: 14px; margin-left: 1px"
          />
        </el-tooltip>
      </div>
      <div
        class="major-right alitem"
        style="display: flex; align-items: center"
      >
        <el-switch
          v-model="isRestrictColorBW"
          @change="
            changeMajorEnrollTypes('isRestrictColorBW', isRestrictColorBW)
          "
          size="small"
          active-text="色盲色弱"
        />
        <el-switch
          style="margin: 0 15px"
          v-model="isRestrictScore"
          size="small"
          active-text="单科成绩"
          @change="changeMajorEnrollTypes('isRestrictScore', isRestrictScore)"
        />
        <el-switch
          v-model="isRestrictLanguage"
          @change="
            changeMajorEnrollTypes('isRestrictLanguage', isRestrictLanguage)
          "
          size="small"
          active-text="语种要求"
        />
      </div>
    </div>

    <el-row class="matop" @click="handleIsShowNoVip" style="margin-top: 10px">
      <el-col :span="12">
        <div class="alitem">
          <div class="major-left">意向专业</div>
          <el-input
            ref="buttonRef"
            v-model="searchKey"
            style="width: 240px"
            placeholder="输入意向专业"
            clearable
            @input="searchKeyInput"
            @focus="isShowSearchPop = true"
            @blur="isShowSearchPop = false"
          >
            <template #prefix>
              <el-icon class="el-input__icon">
                <search />
              </el-icon>
            </template>
          </el-input>
          <div style="margin: 0 6px 0 20px">
            <el-checkbox
              v-model="isAllchecked"
              :label="`用户关注(${specialtyData.length})`"
              size="large"
              @change="toggleAll"
            />
          </div>
          <div style="margin-top: 4px">
            <el-popover
              :visible="visible"
              ref="myPopover"
              placement="bottom"
              :width="180"
              v-model:visible="showPopover"
            >
              <span v-if="specialtyData.length == 0"
                >暂无关注的意向专业...</span
              >
              <div
                style="display: flex; flex-direction: column"
                v-for="(item, index) in specialtyData"
                :key="index"
              >
                <el-checkbox-group v-model="Cities.checkedCities">
                  <el-checkbox
                    @change="changeItem"
                    :value="item"
                    :label="item.name"
                    size="large"
                  />
                </el-checkbox-group>
              </div>

              <div
                style="display: flex; justify-content: flex-end"
                v-if="specialtyData.length != 0"
              >
                <el-button type="primary" size="small" @mousedown="schoolSubmit"
                  >确定</el-button
                >
              </div>

              <template #reference>
                <el-icon
                  @click="visible = !visible"
                  class="el-icon--right"
                  size="16"
                >
                  <ArrowDown />
                </el-icon>
              </template>
            </el-popover>
          </div>
          <div
            v-show="isShowSearchPop && searchList.length > 0"
            class="search-popover"
          >
            <div
              class="curr"
              v-for="(item, index) in searchList"
              :key="index"
              @mousedown="onClickSearchItem(item, index)"
            >
              <div style="padding: 5px 0">
                {{ index == 0 ? '在筛选条件中搜索 "' + item + '"' : item.name }}
              </div>
              <div
                v-if="index + 1 < searchList.length"
                style="width: 100%; height: 1px; background-color: #eee"
              ></div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
  <novip ref="novipRef" />
</template>
<script setup>
import { reactive, ref } from 'vue';
import novip from '@/components/NoVip';
import { allMajor, searchMajor } from '@/api/volunteer/volunteer.js';
import { useStore } from 'vuex';
import _ from 'lodash';
import bus from '@/utils/bus.js';
const novipRef = ref(null);
// const userSearchVal = userSearch()
const emit = defineEmits(['emitMajorEnrollType', 'addMojoyType']);
const store = useStore();

const props = defineProps({
  // 批次线信息
  batchInfo: {
    type: Object,
    default: () => ({}),
  },
  specialtyData: {
    type: Array,
    default: () => [],
  },
  zyType: {
    type: Number,
    required: true,
  },
});
const enrollmentType = ref(1);
const options = ref([
  {
    id: 1,
    name: '不限',
  },
  {
    id: 2,
    name: '仅看',
  },
  {
    id: 3,
    name: '不看',
  },
]);
const dataListType = ref([
  {
    id: 0,
    name: '普通类',
  },
  {
    id: 1,
    name: '专项',
  },
  {
    id: 2,
    name: '师范',
  },
  {
    id: 3,
    name: '扶贫',
  },
  {
    id: 4,
    name: '预科',
  },
  {
    id: 5,
    name: '定向',
  },
  {
    id: 6,
    name: '少数民族',
  },
]);
// const reportingTypeList = ref([
//   {
//     id: 0,
//     name: '色盲色弱',
//   },
//   {
//     id: 1,
//     name: '单科成绩',
//   },
//   {
//     id: 2,
//     name: '语种要求',
//   },
// ]);
const indexNum = ref(-1);
const numXueke = ref(2);
const searchList = ref([]); // 模糊搜索数据源
const majorList = ref([]); // 专业筛选数据源
const selMajors = ref([]); // 选中的专业筛选数据
const checkAll = ref(false);
const tempSelMajors = ref([]);
const searchKey = ref(''); // 搜索关键词
const isShowSearchPop = ref(false); // 是否显示搜索pop
const isAllchecked = ref(false);
const visible = ref(false);
const showPopover = ref(false);
const Cities = reactive({
  checkedCities: [],
});
const isRestrictColorBW = ref(false);
const isRestrictScore = ref(false);
const isRestrictLanguage = ref(false);
const isShow = ref(false);
const majorEnrollTypes = ref([]);

// 招生类型
const handleChange = () => {
  emit('emitMajorEnrollType', {
    majorEnrollTypes: majorEnrollTypes.value,
    enrollmentType: enrollmentType.value,
  });
};
const getStudentsTtype = (item) => {
  if (majorEnrollTypes.value.includes(item.name)) {
    // 如果已选中，则移除

    majorEnrollTypes.value = majorEnrollTypes.value.filter(
      (v) => v.name == item.name,
    );
  } else {
    // 如果未选中，则添加
    majorEnrollTypes.value.push(item.name);
    console.log(' majorEnrollTypes.value:2222222222', majorEnrollTypes.value);
  }

  emit('emitMajorEnrollType', {
    majorEnrollTypes: majorEnrollTypes.value,
    enrollmentType: enrollmentType.value,
  });
};
const addMojoy = () => {
  isShow.value = !isShow.value;
  emit('addMojoyType', isShow.value ? '新增专业' : '');
};
// 特殊报考要求筛选
const changeMajorEnrollTypes = (type, val) => {
  console.log('type, val:', type, val);
  bus.emit('changeMajorEnrollTypes', { key: type, val: val });
};
// 模糊搜索
const searchItem = reactive({
  code: 0,
  name: '',
  type: 'msearch',
});
//切换专业
function tabXueke(num) {
  numXueke.value = num;
  getallMajor();
}

// 监听 props 变化，保持本地副本同步
function getallMajor() {
  const data = {};
  if (numXueke.value !== 1) {
    data.majorsBK = 1;
  } else {
    data.majorsZK = 1;
  }
  allMajor(data).then((res) => {
    if (res.data) {
      majorList.value =
        JSON.parse(JSON.stringify(res.data)).data.majorsBK ||
        JSON.parse(JSON.stringify(res.data)).data.majorsZK;
    }
    // 一键填报数据回显处理
    if (Number(localStorage.getItem('isYJTB')) == 1) {
      // 获取本地存储的专业筛选数据
      let selArr = JSON.parse(localStorage.getItem('majorArrayList')) || [];

      // 循环遍历本地数据和服务器数据code是否相同，相同添加到已选中数组
      selArr.forEach((item) => {
        majorList.value.forEach((major) => {
          const data = major.majors.filter((i) => i.code == item.code);

          if (data.length > 0) {
            selMajors.value.push(data[0]);
          }
        });
      });
    }
  });
}
getallMajor();

// 搜索输入值改变
const searchKeyInput = _.throttle((val) => {
  if (val.length >= 2) {
    searchMajor({
      search: val,
      pageSize: 1000,
    }).then((res) => {
      // console.log('--res--', res)
      searchList.value = res.data.data;

      searchList.value.splice(0, 0, searchKey.value);
      isShowSearchPop.value = true;
    });
  } else {
    searchList.value = [];
    isShowSearchPop.value = false;
  }
}, 800);

/**
 * 点击全选
 * @param {Boolean} val 是否全选
 */
function handleCheckAllChange(val) {
  if (val) {
    let majors = majorList.value[indexNum.value].majors;
    majors.forEach((item) => {
      let arr = tempSelMajors.value.filter((i) => i.code == item.code);

      // 判断是否已存在
      if (arr.length == 0) {
        tempSelMajors.value.push(item);
      }
    });
  } else {
    let majors = majorList.value[indexNum.value].majors;
    majors.forEach((item) => {
      tempSelMajors.value = tempSelMajors.value.filter(
        (i) => i.code != item.code,
      );
    });
  }
  // console.log('--selMajors--', selMajors.value)
}

// 点击单个筛选专业
const handleCheckedCitiesChange = (value) => {
  let item = value[value.length - 1];
  // 判断是否有相同code数据在数组中
  let arr = tempSelMajors.value.filter((i) => i.code == item.code);

  if (arr.length >= 2) {
    // 有相同数据，删除第一个添加的该专业
    let index = tempSelMajors.value.findIndex((i) => i.code == item.code);
    tempSelMajors.value.splice(index, 1);
  }

  checkAllChange();
};

/**
 * 点击专业组
 * @param {Number} val 专业组下标
 */
function clickChange(val) {
  if (store.getters.user.userInfo.isVIP != 0) {
    if (indexNum.value == val) {
      indexNum.value = -1;
      return;
    } else {
      indexNum.value = val;
    }

    // console.log(selMajors.value)
    tempSelMajors.value = JSON.parse(JSON.stringify(selMajors.value));

    checkAllChange();
  } else {
    novipRef.value.handleIsShowDialog();
  }
}
const handleIsShowNoVip = () => {
  if (store.getters.user.userInfo.isVIP == 0) {
    novipRef.value.handleIsShowDialog();
  }
};
// 全选状态改变
function checkAllChange() {
  // 统计当前专业组下已选中专业数
  let majors = majorList.value[indexNum.value].majors;
  let num = 0;
  majors.forEach((item) => {
    let arr = tempSelMajors.value.filter((i) => i.code == item.code);
    num += arr.length;
  });
  // 判断是否全选
  checkAll.value = num >= majors.length;
}

// 确定筛选条件
function onClickCheckboxConfirm() {
  selMajors.value = tempSelMajors.value;
  indexNum.value = -1;

  saveMajorInfo();
}

/**
 * 点击搜素选项
 * @param {Object} item 专业数据
 * @param {Number} index 下标
 */
function onClickSearchItem(item, index) {
  if (index == 0) {
    // 模糊搜索
    searchItem.name = item;
    saveMajorInfo();
  } else {
    // 精准专业搜索
    let index = selMajors.value.findIndex((i) => i.code == item.code);
    if (index < 0) {
      selMajors.value.push(item);
      saveMajorInfo();
    }
  }

  // 添加后清除搜索数据
  searchKey.value = '';
  searchList.value = [];
  isShowSearchPop.value = false;
}
const toggleAll = (val) => {
  // searchArray.value = [];
  if (val) {
    // 全选操作
    if (props.specialtyData.length) {
      props.specialtyData.forEach((v) => {
        v.isChange = true; // 标记为已选
        if (!Cities.checkedCities.includes(v.code)) {
          Cities.checkedCities.push(v);
        }
      });
    }
    // 将选中的项存储到 selItemArray
    if (Cities.checkedCities.length > 0) {
      Cities.checkedCities.forEach((itemCode) => {
        const selectedItem = props.specialtyData.find(
          (item) => item.code === itemCode.code,
        );
        if (selectedItem) {
          console.log('selectedItem:', selectedItem);
          const searchArray = {
            code: selectedItem.code,
            name: selectedItem.name,
            type: 'major',
          };
          let index = selMajors.value.findIndex(
            (i) => i.code == selectedItem.code,
          );
          if (index < 0) {
            selMajors.value.push(searchArray);
            store.dispatch('tianbao/saveMajorInfoChange', selMajors.value);
          }
        }
      });
    }
  } else {
    // 取消全选操作
    props.specialtyData.forEach((v) => {
      v.isChange = false; // 标记为未选
      const index = Cities.checkedCities.indexOf(v);
      if (index !== -1) {
        Cities.checkedCities.splice(index, 1); // 移除已选项
      }
    });
    // 如果取消全选，清空 selItemArray
    selMajors.value = [];
    store.dispatch('tianbao/saveMajorInfoChange', selMajors.value);
  }
  visible.value = false;
};
//专业筛选
const schoolSubmit = () => {
  if (Cities.checkedCities.length !== props.specialtyData.length) {
    isAllchecked.value = false;
  }
  if (Cities.checkedCities.length > 0) {
    Cities.checkedCities.forEach((item) => {
      const selectedItem = {
        code: item.code,
        name: item.name,
        type: 'major',
      };
      let index = selMajors.value.findIndex((i) => i.code == item.code);
      if (index < 0) {
        selMajors.value.push(selectedItem);
        store.dispatch('tianbao/saveMajorInfoChange', selMajors.value);
      }
    });
  }
  visible.value = false;
};
const changeItem = () => {
  isAllchecked.value =
    Cities.checkedCities.length === props.specialtyData.length;
};

// 保存专业筛选数据到仓库
function saveMajorInfo() {
  let searchArray = [];
  selMajors.value.forEach((item) => {
    searchArray.push({
      name: item.name,
      code: item.code,
      type: 'major',
    });
  });

  // 判断是否存在模糊搜索
  if (searchItem.name.length > 0) {
    searchArray.push(searchItem);
  }
  // userSearchVal.saveMajorInfoChange(searchArray); // 保存到 store 中
  store.dispatch('tianbao/saveMajorInfoChange', searchArray);
}

/**
 * 删除某条筛选条件
 * @param {Object} item {type:'类型', code:'id', name:'标题'}
 */
function deleteScreenItem(item) {
  if (item.type == searchItem.type) {
    searchItem.name = '';
  } else {
    selMajors.value = selMajors.value.filter((i) => i.code != item.code);
  }

  saveMajorInfo();
}

function deleteAll() {
  selMajors.value = [];
  tempSelMajors.value = [];
  searchItem.name = '';
  saveMajorInfo();
}
function closeV() {
  visible.value = false;
}
defineExpose({
  deleteScreenItem,
  deleteAll,
  closeV,
});
</script>
<style lang="scss" scoped>
.flexend {
  div {
    font-size: 14px;
    font-weight: 400;
    color: #4e5969;
    line-height: 14px;
    margin-right: 20px;
  }
}

.major-left {
  width: 100px;
  font-size: 14px;
  text-align: center;
  color: #9b9b9b;
}

.major {
  display: flex;
  margin-top: 10px;

  .major-right {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    align-items: center;

    .xueke {
      border: 1px solid #004cf7;
      color: #004cf7;
    }

    .major-size {
      font-size: 14px;
      margin-bottom: 12px;
      padding: 4px 16px;
      margin-right: 10px;
      text-align: center;
      border: 1px solid #e5e6eb;
      border-radius: 4px;
      cursor: pointer;
      color: #4e5969;
    }

    .active {
      border: 1px solid #004cf7;
      color: #004cf7;
    }
  }
}

.search-popover {
  position: absolute;
  top: 40px;
  left: 15px;
  width: 240px;
  height: 200px;
  overflow: auto;
  background-color: white;
  z-index: 999;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  border: 1px solid #c9cdd4;
  padding: 0 10px;
  font-size: 14px;
}

:deep(.el-select--large .el-select__wrapper) {
  min-height: 0 !important;
}
</style>
